package com.vr.cloudpicture.api.imagesearch.sub;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vr.cloudpicture.api.imagesearch.model.ImageSearchResult;
import com.vr.cloudpicture.exception.BusinessException;
import com.vr.cloudpicture.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 获取图像列表 API
 *
 * @author hzh
 * @date 2025/05/20
 */
@Slf4j
public class GetImageListApi {
    /**
     * 获取图像列表
     *
     * @param url 网址
     * @return {@code List<ImageSearchResult> }
     */
    public static List<ImageSearchResult> getImageList(String url) {
        try {
            // 1.发送get请求
            HttpResponse response = HttpUtil.createGet(url).execute();
            // 2.获取响应内容
            if (!response.isOk())  {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"接口调用失败");
            }
            return processResponse(response.body());
        } catch (Exception e) {
            log.error("获取图像列表失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取图像列表失败");
        }
    }

    /**
     * 处理响应内容
     *
     * @param responsebody 接口返回json字符串
     * @return {@code List<ImageSearchResult> }
     */
    private static List<ImageSearchResult> processResponse(String responsebody) {
        JSONObject jsonObject = new JSONObject(responsebody);
        if (!jsonObject.containsKey("data")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未获取到图片列表");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (!data.containsKey("list")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未获取到图片列表");
        }
        JSONArray jsonArray = data.getJSONArray("list");
        return JSONUtil.toList(jsonArray, ImageSearchResult.class);
    }

    public static void main(String[] args) {
        System.out.println(getImageList("https://graph.baidu.com/ajax/pcsimi?carousel=503&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&inspire=general_pc&limit=30&next=2&render_type=card&session_id=1996457687670974128&sign=12680b0520a753a8672ef01747747419&tk=98c38&tpl_from=pc"));
    }
}
